/*
 * @Author: ૮₍ ˙О˙₎ა
 * @Date: 2023-07-13 17:15:35
 */

import router from './router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { useUserInfoStore } from './stores/userInfo'
import getPageTitle from './utils/get-page-title'

const whiteList = ['/login', '/404']
router.beforeEach(async (to, from, next) => {
  // console.log(router.getRoutes())
  // console.log(to.path)

  // 进度条
  NProgress.start()
  document.title = getPageTitle(to.meta.title as string)
  // 获取store内的token
  const useInfoStore = useUserInfoStore()
  const token = useInfoStore.token

  if (token) {
    // 存在token再次跳转登录页到首页
    if (to.path === '/login') {
      next('/')
      NProgress.done()
    } else {
      // 其他页面
      const isName = !!useInfoStore.userInfo.name
      // 用户信息是否存在
      if (isName) {
        next()
      } else {
        try {
          await useInfoStore.getInfo()

          // 动态路由添加
          next(to)
        } catch (error) {
          // 获取用户信息失败
          await useInfoStore.reset()
          next(`/login?redirect=${to.path}`)
        }
      }
      NProgress.done()
    }
  } else {
    // token不存在
    if (whiteList.includes(to.path)) {
      next()
      NProgress.done()
    } else {
      next(`/login`)
      NProgress.done()
    }
  }
})

router.afterEach((to, from) => {
  NProgress.done()
})
